<template>
  <div :class="$style.background">
    <el-row>
      <el-col :span="24">
        <span :class="$style.margin">
          电话状态：
        </span>
        <el-select
          v-model="value"
          placeholder="请选择"
          size="small"
          style="width:100px;"
          @change="handleChangeState">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <span :class="$style.margin" style="cursor:default">
          在线时长：{{time.hours}}时{{time.minutes}}分{{time.seconds}}秒
        </span>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { cookie } from 'vux'
export default {
  data() {
    return {
      options: [{
        value: '在线',
        label: '在线'
      }, {
        value: '暂离',
        label: '暂离'
      },{
        value: '培训',
        label: '培训'
      },{
        value: '开会',
        label: '开会'
      },
      {
        value: '就餐',
        label: '就餐'
      },
      {
        value: '离线',
        label: '离线'
      }
      ],
      value: '离线',
      // preValue:'离线',
      time: {
        seconds: 0,
        minutes: 0,
        hours: 0,
      },
      setInterval: '',
      ws: '',
      setTimeout: '',
      // isError: false
    }
  },
  computed: {
    wsdata () {
      return websocket.data
    },
    userInfo () {
      return this.$store.getters.getUserInfo
    },
    cuUserName(){
      return this.$store.getters.getUserInfo.userName
    }
  },
  watch: {
    cuUserName(val){
      console.log('cuUserName:',val)
      this.getNowTime()
    },
  },
  methods: {
    handleChangeState(val){
      // 只要状态改变都要发送请求
      this.stateHandler(val)
    },
    getTime() {
      this.setInterval= setInterval(() => {
        this.time.seconds++
        if (this.time.seconds == 60) {
          this.time.seconds = 0;
          this.time.minutes++;
        }
        if (this.time.minutes == 60) {
          this.time.minutes = 0;
          this.time.hours++;
        }

      }, 1000)
    },
    clearInterval () {
      clearInterval(this.setInterval);
     
    },
    outLogin() {
      this.$confirm({
        message: '确认要退出吗',
        success: () => {
          this.$get(this, {
            api: 'user/tuiChu.do',
            data: {
              sessionId: this.userInfo.sessionId,
            }
          }).then(({ data }) => {
            if (data.state === 0) {
              cookie.remove('userInfo')
              this.$store.dispatch('outLogin')
              // 退出的时候，移除callMsg
              window.localStorage.removeItem('callMsg')
              //
              sessionStorage.removeItem("refresh")
              this.$router.replace('/')    // 退出登录时，回到首页
              location.reload()
            } else {
              this.$toast({
                message: "退出失败"
              })
            }
          })
        }
      })
    },
    getNowTime () {
      // 获取在线时间
      this.$get(this, {
        api: 'user/getNowTime.do',
        data: {
          username: this.$store.getters.getUserInfo.userName,
        }
      }).then(({ data }) => {
        console.log(data)
        if (data.state === 0) {
          if (data.content) {
            var arr = data.content.split(':');
            this.time.hours = arr[0]
            this.time.minutes = arr[1]
            this.time.seconds = arr[2]
          }
        } else {
          this.$toast({
            message: data.message
          })
        }
      }).catch(e => {
        this.$warn('user/getNowTime.do:',e)
      })
    },
    async stateHandler(state){
      let api
      switch(state){
        case '在线':
          api = 'getOnline'
          break
        case '暂离':
          api = 'getBusy'
          break
        case '开会':
          api = 'getBusy'
          break
        case '培训':
          api = 'getBusy'
          break
        case '就餐':
          api = 'getBusy'
          break
        case '离线':
          api = 'getOffline'
          break
      }
      const { usertel,id } = this.userInfo
      const baseUrl = window.ipurl
      console.log('usertel:', usertel)
      try{
        const {data} = await this.$get(this,{
          api,
          data:{
            Extension:usertel,
            id
          }
        },baseUrl)
        if(data.state === 0){
          this._initWsByState(state)
          this.$toast({
            message:state + '成功'
          })
        } else {
          this.$toast({
            message:state + '失败'
          })
        }
      }catch(e){
        this.$warn(api + e.message)
      }
    },
    _initWsByState(val){
      sessionStorage.setItem("refresh", val);
      if (val === '在线' ||val === '暂离'|| val=== '培训' || val === '开会' ||val ==='就餐') {
        if (websocket.state !== 1) {
          websocket.init(this.userInfo)
        }
        console.log(typeof this.setInterval === 'string')
        if (typeof this.setInterval === 'string') {
          this.getTime();
        }
      }
      if (val === '离线') {
        websocket.reset();
        websocket.ws.close();
        this.clearInterval();
        this.setInterval='';
      }
    },
  },
  mounted() {
    // 初始时若为离线，则做离线处理
    this.getNowTime();
    // this.keepalive();
    if(sessionStorage.getItem("refresh")) {
      this.value = sessionStorage.getItem("refresh")
      if(this.value === '在线'){
        this.handleChangeState(this.value)
      }
    }
  }
}
</script>
<style lang="scss" module>
.background {
  height: 60px;
  padding: 0 10px;
  line-height: 60px;
  overflow: hidden;
  box-sizing: border-box;
  background: #e9e9e9;
  border: 1px solid #444;
  border-radius: 5px;
  box-shadow: 0 1px 3px 2px #666;
  position: fixed;
  right: 0px;
  z-index: 10;
  font-size:14px;
}

.nav {
  overflow: hidden;
  li {
    float: left;
    width: 100px;
    text-align: center;
    cursor: pointer;
    transition: background .3s;
  }
  li:hover {
    background: #404d66;
  }
  .active {
    background: #404d66;
  }
}

.margin {
  margin-left: 10px;
  cursor: pointer;
  height: 30px;
  display: inline-block;
  line-height: 30px;
  img {
    float: left;
    width: 25px;
    margin-right: 5px;
  }
}
</style>
